package com.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.app.common.SystemConstant;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.AttachmentVo;
import com.app.vo.ElectronicVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@RestController
@Controller
@RequestMapping("/api/att")
public class AttachmentController {
    @Autowired
    AttachmentService attachmentService;

    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private MessageService messageService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result<String> upload(
//            @RequestBody JSONObject json,
            HttpServletRequest request
    ) throws IOException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        // 获取文件
        List<MultipartFile> file = ((MultipartHttpServletRequest) request).getFiles("multipart");
        String modelName = params.getParameter("modelName");
        Integer pid = Integer.valueOf(params.getParameter("pid"));
        if (!file.isEmpty()) {
            //上传文件路径
            String path = "";
            path = SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            String fileName = file.get(0).getOriginalFilename();
            int lastIndexOf = fileName.lastIndexOf(".");
            String date = getRandomString2(8);
            //获取文件的后缀名 .jpg
            String suffix = fileName.substring(lastIndexOf);
            String suffix2 = fileName.substring(lastIndexOf + 1);
            File filePath = new File(path + File.separator + date + suffix);
            System.out.println(filePath);
            //如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            //获取文件大小
            //将上传文件保存到一个目标文件中
            file.get(0).transferTo(filePath);
            String fileLength = String.valueOf(filePath.length());
            String fileURL = "";
            fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + date + suffix;
            AttachmentModel model = new AttachmentModel();
            model.setName(fileName);
            model.setAttDir(fileURL);
            model.setAttSize(fileLength);//文件大小
            model.setAttType(suffix2);//文件后缀名
            String[] suffixType1Arr = SystemConstant.DEFAULT_type1.split(",");
            for (int i = 0; i < suffixType1Arr.length; i++) {
                if (suffix2.contains(suffixType1Arr[i])) {
                    model.setFileType(1);
                }
            }
            String[] suffixType2Arr = SystemConstant.DEFAULT_type2.split(",");
            for (int i = 0; i < suffixType2Arr.length; i++) {
                if (suffix2.contains(suffixType2Arr[i])) {
                    model.setFileType(2);
                }
            }
            String[] suffixType3Arr = SystemConstant.DEFAULT_type3.split(",");
            for (int i = 0; i < suffixType3Arr.length; i++) {
                if (suffix2.contains(suffixType3Arr[i])) {
                    model.setFileType(3);
                }
            }
            String[] suffixType4Arr = SystemConstant.DEFAULT_type4.split(",");
            for (int i = 0; i < suffixType4Arr.length; i++) {
                if (suffix2.contains(suffixType3Arr[i])) {
                    model.setFileType(4);
                }
            }
            try {
                model.setPid(pid);
                model.setCreateTime(CommonHelp.getNowTimestamp());
                attachmentService.insert(model);
            } catch (Exception e) {
                System.out.println(e);
            }
//            List<Integer> idList =  departmentService.getDepId(user.getDepartmentId());
//            idList.remove(user.getDepartmentId());
//            if(idList.size()>0 && idList != null) {
//                MessageModel mesModel = new MessageModel();
////                mesModel.setPersonId(user.getId());
//                List<String> stringList = idList.stream().map(String::valueOf).collect(Collectors.toList());
//                String str = String.join(",", stringList);
//                mesModel.setDepartmentId(str);
//                mesModel.setTitle("新文件上传提醒");
//                DepartmentModel departmentModel = departmentService.getDepByDepId(user.getDepartmentId());
//                mesModel.setContent(departmentModel.getName() + " " + user.getRealName() + "上传了一个文件，文件名为" + fileName);
//                mesModel.setCreateTime(CommonHelp.getNowTimestamp());
//                messageService.insert(mesModel);
//            }
            return Result.success(fileURL);
        } else {
            return Result.error(500, "上传失败");
        }

    }

    /**
     * 获取文件列表
     */
    @GetMapping("/getAttachmentList")
    public Result<Object> getAttachmentList(
            HttpServletRequest request,
            Integer page,Integer limit,Integer pid,Integer fileType
    ) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        Page<AttachmentModel> modelPage = attachmentService.getPageAttList(page,limit,pid,fileType);
        AttachmentVo vo = new AttachmentVo();
        vo.setList(modelPage.getRecords());
        vo.setCount((int)modelPage.getTotal());
        return Result.success(vo);
    }

    /**
     * 删除文件
     */
    @GetMapping("/delAttachment")
    public Result<Object> delAttachment(
            HttpServletRequest request,
            String ids
    ) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        //获取ID数组
        String[] str = ids.split(",");
        for (int i = 0; i < str.length; i++) {
            AttachmentModel model = attachmentService.getAttById(Integer.parseInt(str[i]));
            String path = SystemConstant.DEFAULT_UPLOAD_URL;
            String fileName = model.getAttDir().substring(model.getAttDir().lastIndexOf("/")+1);
            File file = new File(path+fileName);
            file.delete();
            attachmentService.delete(Integer.parseInt(str[i]));
        }
        return Result.success("操作成功");
    }

    /**
     * 文件移动
     */
    @PostMapping("/updateAttachment")
    public Result<Object> updateAttachment(
            HttpServletRequest request,
            @RequestBody JSONObject json
    ) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String ids = json.getString("ids");
        Integer pid = Integer.valueOf(json.getString("pid"));
        //获取ID数组
        String str[] = ids.split(",");
        for (int i = 0; i < str.length; i++) {
            AttachmentModel model = attachmentService.getAttById(Integer.valueOf(str[i]));
            model.setPid(pid);
            attachmentService.update(model);
        }
        List<Integer> idList =  departmentService.getDepId(user.getDepartmentId());
        idList.remove(user.getDepartmentId());
//        if(idList.size()>0 && idList != null){
//            MessageModel mesModel = new MessageModel();
//            mesModel.setPersonId(user.getId());
//            mesModel.setDepartmentId(String.valueOf(idList));
//            mesModel.setTitle("新文件上传提醒");
//            DepartmentModel departmentModel = departmentService.getDepByDepId(user.getDepartmentId());
//            mesModel.setContent(departmentModel.getName()+"的"+user.getRealName()+"移动了文件");
//            mesModel.setCreateTime(CommonHelp.getNowTimestamp());
//            messageService.insert(mesModel);
//        }
        return Result.success("操作成功");
    }




    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }


        }
        return sb.toString();
    }

}
